<template>
  <van-config-provider>
    <van-field v-model.number="sms" center clearable :label="store.tel" placeholder="请输入常用手机号" type="number"
      maxlength="11" @update:model-value="handleClick_one">
      <template #button>
        <van-button size="small" type="primary" color="#fb7299" @click="handleGet" :disabled="again">{{ number == 0 ?
          '发送验证码' : `重新发送(${number})`
        }}</van-button>
      </template>
    </van-field>
    <van-field v-model.number="value" label="验证码" placeholder="请输入验证码" maxlength="6" type="number" />
  </van-config-provider>
  <van-config-provider :theme-vars="btn">
    <div class="button">
      <van-button type="primary" block color="#fb7299" :disabled="button" @touchstart="handleLogin">登录 / 注册</van-button>
    </div>
  </van-config-provider>
</template>
<script lang="ts" setup>
import { Button as vanButton, Field as vanField, ConfigProvider as vanConfigProvider, showToast } from 'vant'
import { ref, watch, onBeforeUnmount } from 'vue'
import type { ButtonThemeVars } from 'vant'
import { useRouter } from 'vue-router'
import useTelephoneStore from '@/store/login-telephone.ts'
import axios from 'axios'




const router = useRouter()
const store = useTelephoneStore()


const sms = ref<number>()
const value = ref<number>()
const button = ref<boolean>(true)
const again = ref<boolean>(false)

// 电话号码验证
let one = false

// 验证码，后期可通过异步
let temp = 171529
const btn: ButtonThemeVars = {
  buttonDefaultHeight: '45px'
}

// number ，计数器
let number = ref(0)

// timer， 定时器
let timer = setInterval(() => { })


// 输入电话号码检测函数，只要输入框中的值改变，就会执行
const handleClick_one = () => {

  // 对输入的号码进行验证
  if (JSON.stringify(sms.value).length === 11) {

    // 号码验证通过
    one = true
  }
  else one = false
}

// 获取验证码 按钮
const handleGet = () => {

  // 当电话号码格式正确时
  if (one) {

    // 弹出验证码
    alert('验证码为：\n ' + temp)

    // 将 获取验证码 按钮禁用
    again.value = true

    // 计数器设置大小
    number = ref<number>(30)

    // 定时器
    timer = setInterval(function () {

      // 过一秒，计数器减小 1
      --number.value

      // 当计数器减到 0 时
      if (number.value === 0) {

        // 删除定时器 timer
        clearInterval(timer)

        // 启用 获取验证码 按钮
        again.value = false
      }
    }, 1000)

  }
  else showToast('手机号格式错误')
}

// 点击登录按钮后，出现提示词
const handleLogin = async () => {

  // 当没填写手机号时
  if (!sms.value) showToast('请输入手机号')

  // 当没填写验证码时
  else if (!value.value) showToast('请输入验证码')

  // 当输入手机号格式正确，验证码正确时
  else if (one && value.value === temp) {
    sessionStorage.setItem('token', 'true')
    router.push('/login/user')

    // store.userTel = sms.value.toString()
    sessionStorage.setItem('user', `${sms.value}`)
    const res = await axios({
      method: 'get',
      url: 'http://localhost:3000/users',
    })

    const User = res.data.filter((item: { id: number, account: string, password: string }) => {
      return item.account === sms.value?.toString()
    })

    if (User.length === 0) {
      await axios({
        method: 'post',
        url: 'http://localhost:3000/users',
        data: {
          id: res.data.length + 1,
          account: `${sms.value}`,
          password: '123456'
        }
      })
    }

  }
  else showToast('验证码错误')
}

// 监听 电话号码，验证码
watch(() => [sms.value, value.value], () => {

  // 当填写了 电话号码，验证码，登录按钮就会取消禁用
  button.value = sms.value && value.value ? false : true
})



// 防止一个循环时间，定时器执行两次回调函数
onBeforeUnmount(() => {
  clearInterval(timer)
})

</script>
<style lang="scss" scoped>
.button {
  width: 92vw;
  // height: 20px;
  margin: 17.5px 4vw;
}
</style>